<template>
  <!-- 公司客户基本信息页 -->
  <!-- 最外层容器，添加滚动 -->
  <div class="custom-container">
    <div>{{ console.log('CustInfoDetail 组件已渲染') }}</div>

    <!-- 表单顶部按钮行 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="24" style="text-align: right">
        <div v-if="!isEditMode">
          <el-button type="primary" @click="enterEditMode">编辑</el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表单内容 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- 基础信息 -->
      <div class="base-info">
        <h3>基础信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码：" prop="code">
              <el-input v-model="form.code" readonly />
            </el-form-item>
          </el-col>

          <!-- 公司信息 -->
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="companyName">
              <el-input v-model="form.companyName" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司简称：" prop="companyAbbrevia">
              <el-input v-model="form.companyAbbrevia" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助记名称：" prop="personMnemonicWord">
              <el-input v-model="form.personMnemonicWord" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营范围：" prop="companyRange">
              <el-input v-model="form.companyRange" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司规模：" prop="companyScale">
              <el-input v-model="form.companyScale" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司邮编：" prop="companyPostal">
              <el-input v-model="form.companyPostal" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司电话：" prop="companyPhone">
              <el-input v-model="form.companyPhone" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司传真：" prop="companyFax">
              <el-input v-model="form.companyFax" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司网站：" prop="companyWebsite">
              <el-input v-model="form.companyWebsite" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国家地区：" prop="country">
              <el-input v-model="form.country" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在时区：" prop="timeZone">
              <el-input v-model="form.timeZone" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在城市：" prop="city">
              <el-input v-model="form.city" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="港口：" prop="harbor">
              <el-input v-model="form.harbor" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司地址：" prop="addressPermanent">
              <el-input v-model="form.addressPermanent" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮寄地址：" prop="addressMail">
              <el-input v-model="form.addressMail" :readonly="!isEditMode" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input 
                v-model="form.remark" 
                :readonly="!isEditMode" 
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 分类信息 -->
      <div class="classification-info">
        <h3>分类信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户来源：" prop="source">
              <el-input v-if="!isEditMode" v-model="form.sourceCode" readonly />
              <el-select
                v-else
                v-model="form.sourceCode"
                placeholder="请选择客户来源"
                clearable
                filterable
              >
                <el-option
                  v-for="item in sourceOptions"
                  :key="item.code"
                  :label="item.source"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业分类：" prop="industry">
              <el-input v-if="!isEditMode" v-model="form.industryCode" readonly />
              <el-select
                v-else
                v-model="form.industryCode"
                placeholder="请选择行业分类"
                clearable
                filterable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户优先级：" prop="priority">
              <el-input v-if="!isEditMode" v-model="form.priorityCode" readonly />
              <el-select
                v-else
                v-model="form.priorityCode"
                placeholder="请选择客户优先级"
                clearable
                filterable
              >
                <el-option
                  v-for="item in priorityOptions"
                  :key="item.code"
                  :label="item.priority"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户星级：" prop="star">
              <el-input v-if="!isEditMode" v-model="form.starCode" readonly />
              <el-select
                v-else
                v-model="form.starCode"
                placeholder="请选择客户星级"
                clearable
                filterable
              >
                <el-option
                  v-for="item in starOptions"
                  :key="item.code"
                  :label="item.star"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户阶段：" prop="stage">
              <el-input v-if="!isEditMode" v-model="form.stageCode" readonly />
              <el-select
                v-else
                v-model="form.stageCode"
                placeholder="请选择客户阶段"
                clearable
                filterable
              >
                <el-option
                  v-for="item in stageOptions"
                  :key="item.code"
                  :label="item.stage"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户状态：" prop="status">
              <el-input v-if="!isEditMode" v-model="form.statusCode" readonly />
              <el-select
                v-else
                v-model="form.statusCode"
                placeholder="请选择客户状态"
                clearable
                filterable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.code"
                  :label="item.status"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <!-- 新增联系人区块 -->
    <div class="contacts-info" :key="contactsListKey">
      <h3>联系人</h3>

      <cust-contacts-form
        v-model="dialogVisible"
        :cust-id="form.id"
        @save-success="handleContactSaveSuccess"
      />

      <el-row :gutter="20" style="margin-bottom: 20px; text-align: left">
        <el-col :span="8">
          <div>
            <el-button type="primary" @click="showDialog">新增</el-button>

            <!-- <el-button
              type="primary"
              @click="handleEditContact"
              :disabled="selectedContacts.length !== 1"
              >编辑</el-button
            > -->
            <el-button
              type="primary"
              @click="handleDeleteContacts"
              :disabled="selectedContacts.length === 0"
              >删除</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-table
        v-if="contactsList.length > 0"
        :data="contactsList"
        border
        style="width: 100%; overflow-x: auto"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" width="100">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="100">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="60">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.sex }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职务" width="100">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.position }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="150">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="landline" label="座机" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.landline }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="移动电话" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="facebook" label="Facebook" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.facebook }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ins" label="ins" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.ins }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="tiktok" label="TIKTOK" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.tiktok }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="youtube" label="Youtube" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.youtube }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="linkedin" label="Linkedin" width="120">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.linkedin }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注">
          <template #default="scope">
            <span style="white-space: nowrap">{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 其他信息区块 -->
    <div class="other-info">
      <h3>其他信息</h3>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="label">创建人：</span>
            <span class="value">{{ form.creator }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">归属业务员：</span>
            <span class="value">{{ form.salesman }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formattedCreateTime }}</span>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CustInfoApi, CustInfoVO } from '@/api/customermanager/custmanage'
import { defineProps } from 'vue'

import { CustContactsApi } from '@/api/customermanager/custcontacts' // 联系人API导入
import type { CustContactsVO } from '@/api/customermanager/custcontacts' // 联系人类型导入

import CustContactsForm from './CustContactsForm.vue'

// 客户来源相关导入
import { BaseCustSourceApi, type BaseCustSourceVO } from '@/api/business/basecustsource'
// 客户优先级相关导入
import { BaseCustPriorityApi, type BaseCustPriorityVO } from '@/api/business/basecustpriority'

import { BaseCustStatusApi, type BaseCustStatusVO } from '@/api/business/basecuststatus'

import { BaseCustStarApi, type BaseCustStarVO } from '@/api/business/basecuststar'

import {
  BaseCustIndustryClassApi,
  type BaseCustIndustryClassVO
} from '@/api/business/basecustindustryclass'

import { BaseCustStageApi, type BaseCustStageVO } from '@/api/business/basecuststage'

// 客户来源选项数据
const sourceOptions = ref<BaseCustSourceVO[]>([])

// 客户优先级选项数据
const priorityOptions = ref<BaseCustPriorityVO[]>([])

// 客户状态选项数据
const statusOptions = ref<BaseCustStatusVO[]>([])

// 客户星级选项数据
const starOptions = ref<BaseCustStarVO[]>([])

// 行业分类选项数据
const industryOptions = ref<BaseCustIndustryClassVO[]>([])

// 客户阶段选项数据
const stageOptions = ref<BaseCustStageVO[]>([])

// 获取客户来源数据
const getSourceOptions = async () => {
  try {
    const res = await BaseCustSourceApi.getBaseCustSourcePage({})
    sourceOptions.value = res.list || []
  } catch (error) {
    ElMessage.error('获取客户来源数据失败')
  }
}
// 获取客户优先级数据
const getPriorityOptions = async () => {
  try {
    const res = await BaseCustPriorityApi.getBaseCustPriorityPage({})
    priorityOptions.value = res.list || []
  } catch (error) {
    ElMessage.error('获取客户优先级数据失败')
  }
}

// 获取客户状态数据
const getStatusOptions = async () => {
  try {
    const res = await BaseCustStatusApi.getBaseCustStatusPage({})
    statusOptions.value = res.list || []
  } catch (error) {
    ElMessage.error('获取客户状态数据失败')
  }
}

// 获取客户星级数据
const getStarOptions = async () => {
  try {
    const res = await BaseCustStarApi.getBaseCustStarPage({})
    starOptions.value = res.list || []
  } catch (error) {
    ElMessage.error('获取客户星级数据失败')
  }
}

// 获取行业分类数据
const getIndustryOptions = async () => {
  try {
    const res = await BaseCustIndustryClassApi.getBaseCustIndustryClassList({})
    industryOptions.value = res || []
  } catch (error) {
    ElMessage.error('获取行业分类数据失败')
  }
}

// 获取客户阶段数据
const getStageOptions = async () => {
  try {
    const res = await BaseCustStageApi.getBaseCustStagePage({})
    stageOptions.value = res.list || []
  } catch (error) {
    ElMessage.error('获取客户阶段数据失败')
  }
}

const route = useRoute()
const router = useRouter()

const contactsListKey = ref(0) // key 控制联系人刷新

// 新增联系人弹窗
const dialogVisible = ref(false)
// const showDialog = () => {
//   console.log('showDialog 被点击')
//   dialogVisible.value = true
// }

const showDialog = () => {
  console.log('showDialog 被点击')
  console.log('当前 form.id:', form.id)

  if (!form.id || form.id === 0) {
    ElMessage.warning('请先保存客户基本信息')
    return
  }

  dialogVisible.value = true
}

// 在 CustInfoDetail.vue 中，通过 props 或 route.query 接收 cust_id
const props = defineProps({
  custId: {
    type: [Number, String],
    required: true
  }
})

// 表单数据
const form = reactive<CustInfoVO>({
  id: 0,
  code: '',
  personName: '',
  personMnemonicWord: '',
  personSex: '',
  personEmail: '',
  personLandline: '',
  personPhone: '',
  personFacebook: '',
  personIns: '',
  personTiktok: '',
  personYoutube: '',
  personLinkedin: '',
  personPostalCode: '',
  companyName: '',
  companyAbbrevia: '',
  companyRange: '',
  companyScale: '',
  companyPostal: '',
  companyPhone: '',
  companyFax: '',
  companyWebsite: '',
  country: '',
  timeZone: '',
  city: '',
  harbor: '',
  addressPermanent: '',
  addressMail: '',
  sourceCode: '',
  industryCode: '',
  priorityCode: '',
  starCode: '',
  stageCode: '',
  statusCode: '',
  remark: '',
  salesman: '',
  creator: '',
  createTime: '',
  typeCode: ''
})

// 是否为编辑模式
const isEditMode = ref(false)

// 表单引用
const formRef = ref()

// 规则
const rules = {
  // 可以根据需要添加验证规则
}

// 获取客户信息
const getCustInfo = async (id: number) => {
  console.log('基础信息页获得id:', id)
  if (!id) {
    ElMessage.warning('无效的客户 ID')
    return
  }
  try {
    const result = await CustInfoApi.getCustInfo(id)
    Object.assign(form, result)
    console.log('获取到的客户信息:', form) // 确认数据是否正确加载
  } catch (error) {
    ElMessage.error('获取客户信息失败')
  }
}

// 进入编辑模式
const enterEditMode = () => {
  isEditMode.value = true
  // 进入编辑模式时获取客户来源数据
  getSourceOptions()
  // 进入编辑模式时获取客户优先级数据
  getPriorityOptions()
  // 进入编辑模式时获取客户状态数据
  getStatusOptions()
  // 进入编辑模式时获取客户星级数据
  getStarOptions()
  // 进入编辑模式时获取行业分类数据
  getIndustryOptions()
  // 进入编辑模式时获取客户阶段数据
  getStageOptions()
}

// 保存客户信息
const save = async () => {
  try {
    await formRef.value.validate()

    const result = await CustInfoApi.updateCustInfo(form as CustInfoVO)

    // 如果API返回了新的ID，更新form.id
    if (result && result.id) {
      form.id = result.id
      console.log('更新后的 form.id:', form.id)
    }

    ElMessage.success('保存成功')
    isEditMode.value = false

    await getCustInfo(form.id) // 刷新客户信息
    await fetchData() // 刷新联系人列表
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消编辑
const cancel = () => {
  isEditMode.value = false
  // 优先使用 props.custId，如果没有则尝试使用路由参数
  const custId = props.custId || (route.query.cust_id ? Number(route.query.cust_id) : null)
  if (custId) {
    getCustInfo(custId)
  } else {
    ElMessage.warning('无法获取客户信息：无效的客户ID')
  }
}

// 处理 keep-alive 缓存组件的情况
onActivated(() => {
  if (props.custId) {
    getCustInfo(props.custId)
  }
})

// 新增联系人数据
const contactsList = ref<CustContactsVO[]>([]) // 联系人列表

// 新增：获取联系人列表方法
const fetchContacts = async (custId: number) => {
  if (!custId) {
    ElMessage.warning('无效的客户 ID')
    return
  }
  try {
    const response = await CustContactsApi.listByCustId({ custId: custId })

    // response 是已经提取过 data 的数据，直接使用
    contactsList.value = Array.isArray(response) ? response : []
    if (!contactsList.value.length) {
      ElMessage.warning('联系人数据为空')
    }
  } catch (error) {
    console.error('获取联系人失败:', error)
    ElMessage.error('获取联系人失败')
  }
}

// 封装同时获取客户信息和联系人的方法
const fetchAllData = (custId: number) => {
  getCustInfo(custId)
  fetchContacts(custId)
}

const selectedContacts = ref<CustContactsVO[]>([])

const handleSelectionChange = (selection: CustContactsVO[]) => {
  selectedContacts.value = selection
}

// 处理联系人保存成功的方法
const handleContactSaveSuccess = async () => {
  ElMessage.success('联系人保存成功')

  // 确保使用有效的客户ID
  const customerId = form.id || props.custId
  if (customerId) {
    await fetchData(customerId)
  } else {
    ElMessage.warning('无法刷新联系人列表')
  }
}

const handleEditContact = () => {
  if (selectedContacts.value.length === 1) {
    const contact = selectedContacts.value[0]
    // 调用编辑联系人的逻辑
    console.log('编辑联系人', contact)
  }
}

// 处理联系人保存成功的方法 1
const handleDeleteContacts = async () => {
  if (selectedContacts.value.length > 0) {
    try {
      const ids = selectedContacts.value.map((contact) => contact.id)
      await CustContactsApi.deleteCustContacts(ids)
      ElMessage.success('删除成功')

      // 重新获取联系人列表
      // fetchContacts(props.custId)
      // 检查 custId 是否有效
      if (form.id) {
        fetchContacts(form.id)
      } else {
        ElMessage.warning('无效的客户 ID，在刷新联系人时')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  console.log('当前路由信息:', route)
  console.log('查询参数:', route.query)

  // 如果路由参数中有cust_id，使用它获取数据
  if (route.query.cust_id) {
    const custId = Number(route.query.cust_id)
    if (!isNaN(custId)) {
      fetchAllData(custId)
    }
  }
  // 如果props中有custId，使用它获取数据
  else if (props.custId) {
    fetchAllData(props.custId)
  }
})

// 修改 fetchData 方法，支持传入 custId 1
const fetchData = async (custId?: number) => {
  console.log('=== fetchData 被调用 ===')
  console.log('传入的 custId:', custId)
  console.log('props.custId:', props.custId)
  console.log('form.id:', form.id)

  const customerId = custId || props.custId || form.id

  if (customerId) {
    console.log('使用客户ID获取联系人:', customerId)
    await fetchContacts(customerId)
    contactsListKey.value++ // 更新 key，触发重新渲染
    await nextTick() // 等待 DOM 更新
    console.log('联系人列表已刷新，当前联系人数量:', contactsList.value.length)
  } else {
    console.warn('无法刷新联系人列表：客户ID无效')
  }
}

// 监听 custId 变化
watch(
  () => props.custId,
  (newId) => {
    if (newId) {
      console.log('watch 触发，newId:', newId)
      getCustInfo(newId)
    }
  },
  { immediate: true }
)

// 计算属性：格式化创建时间
const formattedCreateTime = computed(() => {
  if (!form.createTime) return '' // 如果 createTime 为空，返回空字符串

  // 将 createTime（假设为 Unix 时间戳）转换为 Date 对象
  const date = new Date(Number(form.createTime))
  // 使用 toLocaleString 方法格式化日期时间
  return date.toLocaleString()
})
</script>

<style scoped>
/* 最外层容器，设置最大高度和垂直滚动 */
.custom-container {
  max-height: calc(100vh - 100px); /* 根据你的布局调整 */
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}

.base-info,
.classification-info {
  margin-bottom: 20px;
}

h3 {
  margin-bottom: 10px;
}

/* 新增联系人区块样式 */
.contacts-info {
  margin-bottom: 20px;
}

.contacts-info h3 {
  margin-bottom: 10px;
}

.other-info {
  margin-bottom: 20px;
}

.other-info h3 {
  margin-bottom: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.value {
  flex: 1;
}

/* 统一设置表格单元格内容不换行 */
.el-table .cell {
  white-space: nowrap;
}
</style>
